package cn.ydw.community.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日志处理类
 */
@Aspect
@Component
@Slf4j
public class ServiceAspect {

    @Pointcut("execution(* cn.ydw.community.service.*.*(..))")
    public void pointCut(){}

    @Before("pointCut()")
    public void beforePoint(JoinPoint joinPoint){
        // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String remoteAddr = request.getRemoteHost();
        // 获取类名
        String typeName = joinPoint.getSignature().getDeclaringTypeName();
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        log.info("用户" + remoteAddr + "在[" + date + "]访问了" + typeName  +"." + methodName);
    }
}
